/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tolls;

import avenue.MyWindowEvent;
import avenue.Session;
import avenue.Utils;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.math.BigDecimal;
import java.util.Date;
import javax.swing.JTextField;
import model.DBManager;
import model.Payment;
import model.Vehicle;

/**
 *
 * @author Aggelos
 */
public class PaymentForm extends javax.swing.JFrame {

    /**
     * Creates new form PaymentForm
     */
    private Vehicle vehicle;
    private double amount = 0;
    private double newBalance = 0;

    private void checkControls() {

        jTxtNewBalance.setText(String.format("%.2f", newBalance));
        jBtnPay.setEnabled(amount >= 10.0f);
        if (!jBtnPay.isEnabled()) {
            jLbMessage.setText(Utils.msgLowAmmount);
        } else {
            jLbMessage.setText("");
            this.getRootPane().setDefaultButton(jBtnPay);
        }
    }

    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);

    }

    public PaymentForm() {
        initComponents();
        jTxtNewBalance.setHorizontalAlignment(JTextField.RIGHT);
        jTxtBalance.setHorizontalAlignment(JTextField.RIGHT);
        jTxtAmount.setHorizontalAlignment(JTextField.RIGHT);
        checkControls();
    }

    public PaymentForm(Vehicle v) {
        initComponents();
        Utils.centerOnScreen(this);
        jTxtNewBalance.setHorizontalAlignment(JTextField.RIGHT);
        jTxtBalance.setHorizontalAlignment(JTextField.RIGHT);
        jTxtAmount.setHorizontalAlignment(JTextField.RIGHT);
        vehicle = v;
        jTxtRegNumber.setText(v.getRegNumber());
        jTxtCard.setText(String.format("%s", v.getCardId().getBarcode()));
        jTxtBalance.setText(String.format("%.2f", v.getCardId().getBalance()));
        jLbMessage.setText("");

        
        checkControls();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBtnPay = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTxtCard = new javax.swing.JTextField();
        jTxtRegNumber = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTxtNewBalance = new javax.swing.JTextField();
        jBtnCancel = new javax.swing.JButton();
        jTxtBalance = new javax.swing.JTextField();
        jTxtAmount = new javax.swing.JTextField();
        jLbMessage = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Πληρωμή κάρτας");
        setResizable(false);

        jBtnPay.setText("Πληρωμή");
        jBtnPay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnPayActionPerformed(evt);
            }
        });

        jLabel4.setText("Ποσό Πληρωμής:");

        jLabel5.setText("Νέο Υπόλοιπο:");

        jLabel1.setText("Αρ. Κυκλοφορίας: ");

        jLabel2.setText("Αρ. Κάρτας: ");

        jTxtCard.setEditable(false);
        jTxtCard.setBackground(new java.awt.Color(204, 204, 204));
        jTxtCard.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        jTxtRegNumber.setEditable(false);
        jTxtRegNumber.setBackground(new java.awt.Color(204, 204, 204));
        jTxtRegNumber.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        jLabel6.setText("Υπόλοιπο Κάρτας: ");

        jTxtNewBalance.setEditable(false);
        jTxtNewBalance.setBackground(new java.awt.Color(255, 204, 255));
        jTxtNewBalance.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        jBtnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jBtnCancel.setText("Ακυρο");
        jBtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelActionPerformed(evt);
            }
        });

        jTxtBalance.setEditable(false);
        jTxtBalance.setBackground(new java.awt.Color(255, 204, 255));
        jTxtBalance.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        jTxtAmount.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jTxtAmount.setForeground(new java.awt.Color(0, 51, 153));
        jTxtAmount.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTxtAmountKeyReleased(evt);
            }
        });

        jLbMessage.setForeground(new java.awt.Color(255, 0, 0));
        jLbMessage.setText("jLabel3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTxtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTxtNewBalance, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTxtRegNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTxtCard, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTxtBalance, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jBtnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                            .addComponent(jBtnPay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLbMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTxtAmount, jTxtNewBalance});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTxtBalance, jTxtCard, jTxtRegNumber});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTxtRegNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTxtCard, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(7, 7, 7)
                                .addComponent(jLabel6))
                            .addComponent(jTxtBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTxtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jBtnPay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTxtNewBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGap(18, 18, 18)
                        .addComponent(jLbMessage))
                    .addComponent(jBtnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jTxtAmount, jTxtNewBalance});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jTxtBalance, jTxtCard, jTxtRegNumber});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelActionPerformed
        // TODO add your handling code here:
        closeMe(false);
    }//GEN-LAST:event_jBtnCancelActionPerformed

    private void jTxtAmountKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtAmountKeyReleased

        try {
            if (jTxtAmount.getText().trim().equals("")) {
                amount = 0;
                newBalance = vehicle.getCardId().getBalance();
            } else {
                amount = Float.parseFloat(jTxtAmount.getText());
                newBalance = amount + vehicle.getCardId().getBalance();
            }
        } catch (Exception ex) {
            amount = 0;
            newBalance = vehicle.getCardId().getBalance();
        }

        checkControls();
    }//GEN-LAST:event_jTxtAmountKeyReleased

    private void jBtnPayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPayActionPerformed
        if (!Utils.acceptNumbersOnly(jTxtAmount.getText())) {
            return;
        }
        Payment p = new Payment();
        p.setCardId(vehicle.getCardId());

        p.setOldBalance(BigDecimal.valueOf(vehicle.getCardId().getBalance()));
        p.setAmount(BigDecimal.valueOf(amount));
        p.setPaymentTimestamp(new Date());
        p.setStationId(Session.loginUser.getStationId());

        vehicle.getCardId().setBalance(newBalance);
        DBManager.em.persist(p);
        DBManager.em.persist(vehicle.getCardId());

        DBManager.em.getTransaction().commit();
        DBManager.em.getTransaction().begin();
        closeMe(true);
    }//GEN-LAST:event_jBtnPayActionPerformed
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;






                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaymentForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PaymentForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnCancel;
    private javax.swing.JButton jBtnPay;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLbMessage;
    private javax.swing.JTextField jTxtAmount;
    private javax.swing.JTextField jTxtBalance;
    private javax.swing.JTextField jTxtCard;
    private javax.swing.JTextField jTxtNewBalance;
    private javax.swing.JTextField jTxtRegNumber;
    // End of variables declaration//GEN-END:variables
}
